//
//  SXToast.m
//  SXDataManager-SXDataManager
//
//  Created by wangshuixin on 2019/1/19.
//

#import "SXToast.h"

// 判空
#define SXPREDICATE_EMPTY_OBJECT(_obj) (_obj == nil || _obj.length == 0)
@interface SXToast ()

@property (strong, nonatomic) UILabel *messageLabel;
@property (assign, nonatomic) CGFloat maxWidth;
@property (assign, nonatomic) CGFloat maxHeight;

@end

@implementation SXToast

+ (instancetype)sharedInstance {
    static SXToast *instance = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [[self alloc] init];
    });
    return instance;
}

#pragma mark - Lifecycle
- (instancetype)init {
    if (self = [super init]) {
        self.backgroundColor = [UIColor cyanColor];
        [self initDefaultProperty];
        [self showMessageToSuperView];
    }
    return self;
}

#pragma mark - Init Default Property
- (void)initDefaultProperty {
    if (!self.maxWidth) {
        self.maxWidth = [UIScreen mainScreen].bounds.size.width - 40;
    }
    if (!self.maxHeight) {
        self.maxHeight = [UIScreen mainScreen].bounds.size.height - 220;
    }
}

// 设置toastView的最大宽度和最大高度
+ (void)makeToastViewMaxWidth:(CGFloat)maxWidth maxHeight:(CGFloat)maxHeight {
    SXToast *toast = [SXToast sharedInstance];
    toast.maxWidth = maxWidth;
    toast.maxHeight = maxHeight;
}

// 设置toastView的最大宽度和最大高度
+ (void)makeToastViewMaxArea:(NSDictionary *)areaDict {
    SXToast *toast = [SXToast sharedInstance];
    toast.maxWidth = [areaDict[@"maxWidth"] floatValue];
    toast.maxHeight = [areaDict[@"maxHeight"] floatValue];
}

#pragma mark - Draw View methods
- (void)showMessageToSuperView {
    UILabel *messageLabel = [[UILabel alloc] initWithFrame:CGRectZero];
    messageLabel.font = [UIFont fontWithName:@"PingFangSC-Regular" size:15];
    messageLabel.textColor = [UIColor whiteColor];
    messageLabel.numberOfLines = 0;
    messageLabel.backgroundColor = [UIColor colorWithWhite:0 alpha:0.7];
    messageLabel.layer.cornerRadius = 5;
    messageLabel.layer.masksToBounds = YES;
    self.messageLabel = messageLabel;
    UIWindow *window = [SXToast currentWindow];
    [window addSubview:messageLabel];
}

#pragma mark - Class methods
// 在window上显示一个纯文本的toast
+ (void)showToast:(NSString *)message duration:(CGFloat)duration location:(nullable NSString *)location {
    if (SXPREDICATE_EMPTY_OBJECT(message)) {
        NSAssert(NO, @"you should set a text for showView!");
        return;
    }
    NSAssert([NSThread isMainThread], @"needs to be accessed on the main thread!");
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^(void) {
        });
    }
    SXToast *toast = [[SXToast alloc] init];
    SXToast *toastShare = [SXToast sharedInstance];
    NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    // 对齐方式
    style.alignment = NSTextAlignmentJustified;
    style.lineBreakMode = NSLineBreakByTruncatingTail;
    // 首行缩进
    style.firstLineHeadIndent = 10.0f;
    // 头部缩进
    style.headIndent = 10.0f;
    // 尾部缩进
    style.tailIndent = -10.0f;
    NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:message attributes:@{ NSParagraphStyleAttributeName : style}];
    toast.messageLabel.attributedText = attrText;
    toast.messageLabel.hidden = NO;
    CGFloat width = [SXToast convertToContentWidthOfSizeFromTextMessage:toast.messageLabel.text font:toast.messageLabel.font maxWidth:toastShare.maxWidth];
    CGFloat height = [SXToast convertToContentHeightOfSizeFromTextMessage:message font:toast.messageLabel.font maxWidth:toastShare.maxWidth];
    height = height >= toastShare.maxHeight ? toastShare.maxHeight : height;
    toast.messageLabel.frame = CGRectMake(0, 0, width + 20, height + 10);
    UIWindow *window = [SXToast currentWindow];
    [window addSubview:toast];
    if ([location isEqualToString:@"center"]) {
        toast.messageLabel.center = toast.superview.center;
    } else if ([location isEqualToString:@"top"]) {
        toast.messageLabel.center = CGPointMake(toast.superview.center.x, 120 + height/2);
    } else if ([location isEqualToString:@"bottom"]) {
        toast.messageLabel.center = CGPointMake(toast.superview.center.x, window.frame.size.height - 105 - height/2);
    } else {
        toast.messageLabel.center = toast.superview.center;
    }
    [SXToast managerTimerDuration:duration frequency:0.1 onToast:toast];
}

// 在window上显示一个纯文本的toast
+ (void)showToastByRule:(NSDictionary *)ruleDict {
    NSString *message = ruleDict[@"message"];
    CGFloat duration = [ruleDict[@"duration"] floatValue];
    NSString *location = ruleDict[@"location"];
    if (SXPREDICATE_EMPTY_OBJECT(message)) {
        NSAssert(NO, @"you should set a text for showView!");
        return;
    }
    if (duration <= 0) {
        NSAssert(NO, @"you should set a duration for showView!");
        return;
    }
    NSAssert([NSThread isMainThread], @"needs to be accessed on the main thread!");
    if (![NSThread isMainThread]) {
        dispatch_async(dispatch_get_main_queue(), ^(void) {
        });
    }
    SXToast *toast = [[SXToast alloc] init];
    SXToast *toastShare = [SXToast sharedInstance];
    NSMutableParagraphStyle *style = [[NSParagraphStyle defaultParagraphStyle] mutableCopy];
    // 对齐方式
    style.alignment = NSTextAlignmentJustified;
    style.lineBreakMode = NSLineBreakByTruncatingTail;
    // 首行缩进
    style.firstLineHeadIndent = 10.0f;
    // 头部缩进
    style.headIndent = 10.0f;
    // 尾部缩进
    style.tailIndent = -10.0f;
    NSAttributedString *attrText = [[NSAttributedString alloc] initWithString:message attributes:@{ NSParagraphStyleAttributeName : style}];
    toast.messageLabel.attributedText = attrText;
    toast.messageLabel.hidden = NO;
    CGFloat width = [SXToast convertToContentWidthOfSizeFromTextMessage:toast.messageLabel.text font:toast.messageLabel.font maxWidth:toastShare.maxWidth];
    CGFloat height = [SXToast convertToContentHeightOfSizeFromTextMessage:message font:toast.messageLabel.font maxWidth:toastShare.maxWidth];
    height = height >= toastShare.maxHeight ? toastShare.maxHeight : height;
    toast.messageLabel.frame = CGRectMake(0, 0, width + 20, height + 10);
    UIWindow *window = [SXToast currentWindow];
    [window addSubview:toast];
    if ([location isEqualToString:@"center"]) {
        toast.messageLabel.center = toast.superview.center;
    } else if ([location isEqualToString:@"top"]) {
        toast.messageLabel.center = CGPointMake(toast.superview.center.x, 120 + height/2);
    } else if ([location isEqualToString:@"bottom"]) {
        toast.messageLabel.center = CGPointMake(toast.superview.center.x, window.frame.size.height - 105 - height/2);
    } else {
        toast.messageLabel.center = toast.superview.center;
    }
    [SXToast managerTimerDuration:duration frequency:0.1 onToast:toast];
}

// NSTimer定时器倒计时
+ (void)managerTimerDuration:(CGFloat)duration frequency:(CGFloat)frequency onToast:(SXToast *)toast {
    __block CGFloat timeout = duration;
    __block CGFloat timeFrequency = frequency;
    dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    dispatch_source_t timer = dispatch_source_create(DISPATCH_SOURCE_TYPE_TIMER, 0, 0,queue);
    dispatch_source_set_timer(timer,dispatch_walltime(NULL, 0),timeFrequency*NSEC_PER_SEC, 0); //执行频率：frequency
    dispatch_source_set_event_handler(timer, ^{
        if(timeout <= 0) { //倒计时结束，关闭
            dispatch_source_cancel(timer);
            dispatch_async(dispatch_get_main_queue(), ^{
                toast.messageLabel.hidden = YES;
            });
        } else {
            dispatch_async(dispatch_get_main_queue(), ^{
                
            });
            timeout -= timeFrequency;
        }
    });
    dispatch_resume(timer);
}

//获取当前window
+ (UIWindow *)currentWindow {
    UIApplication *app = [UIApplication sharedApplication];
    if ([app.delegate respondsToSelector:@selector(window)]) {
        return [app.delegate window];
    } else {
        return [app keyWindow];
    }
}

// 获取固定message显示到控件上所占size.width
+ (CGFloat)convertToContentWidthOfSizeFromTextMessage:(NSString *)message font:(UIFont *)font maxWidth:(CGFloat)maxWidth {
    CGSize size = [message sizeWithAttributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil]];
    if (!maxWidth) {
        maxWidth = 0;
    }
    CGFloat width = size.width <= maxWidth ? size.width : maxWidth;
    return width;
}

// 获取固定message显示到控件上所占size.height
+ (CGFloat)convertToContentHeightOfSizeFromTextMessage:(NSString *)message font:(UIFont *)font maxWidth:(CGFloat)maxWidth {
    CGFloat contentW = [SXToast convertToContentWidthOfSizeFromTextMessage:message font:font maxWidth:maxWidth];
    contentW = contentW <= [UIScreen mainScreen].bounds.size.width - 40 ? contentW : [UIScreen mainScreen].bounds.size.width - 40;
    CGRect rect = [message boundingRectWithSize:CGSizeMake(contentW, 1000) options:NSStringDrawingUsesLineFragmentOrigin attributes:[NSDictionary dictionaryWithObjectsAndKeys:font,NSFontAttributeName, nil] context:nil];
    return rect.size.height;
}

@end
